<?php

namespace App\Admin\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use App\crm_order;
use App\crm_customer;
use App\Admin_users;
use App\crm_route;
use App\crm_biaoqian;
use App\crm_deal;
use App\crm_supplier;
use App\crm_huifang;
use App\crm_receive;
use App\crm_account;
use App\crm_funds;
use App\crm_tourist;
use App\supplier_type;
use App\crm_hetongtype;
use App\crm_hetong;
use App\crm_diaocha;
use App\crm_dchuifang;
use App\crm_manyidu;
use Validator;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Column;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use App\Admin\Extensions\Tools\XiadanGender;
use App\Admin\Extensions\Tools\YixiangGender;
use App\Admin\Extensions\Tools\YixiangtianjiaGender;
use App\Admin\Extensions\Tools\ManyiduGender;
use App\Admin\Extensions\Tools\ManyixiangqingGender;
use App\Admin\Extensions\Tools\ShoukuanGender;
use App\Admin\Extensions\Tools\QingkuanGender;
use App\Admin\Extensions\Tools\HesuanGender;
use App\Admin\Extensions\Tools\JxhesuanGender;
use App\Admin\Extensions\Tools\CwhesuanGender;
use App\Admin\Extensions\Tools\YhesuanGender;
use App\Admin\Extensions\Tools\LktianjiaGender;
use App\Admin\Extensions\Tools\LkshangchuanGender;
use App\Admin\Extensions\Tools\XinzengGender;
use Maatwebsite\Excel\Facades\Excel;
class Crm_orderController extends Controller
{
    use ModelForm;

    // 列表
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('工单管理');
            $content->description('工单列表');
            $content->body($this->grid());
        });
    }

    // 显示页面
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('工单管理');
            $content->description('详情');
            $content->row(function (Row $row) use ($id) {
                $row->column(12, function (Column $column) use ($id) {
                    $tab = new Tab();
                    $list=crm_order::find($id);
                    $tab->add('客户详情', $this->kehu($list->order_customerid));
                    $tab->add('工单详情', $this->gongdan($id));
                    $tab->add('跟单记录',$this->huifang($id));
                    $url=json_encode(admin_url('crm_order/'.$id."/create"));
                    $script_three=<<<EOT
                        $(".fa-save").parent().attr("href",$url);
                        $(".header").html('<a href="javascript:" id="fanhui">返回</a>');
                        $(".header").click(function(){
                          window.history.back();
                        });

EOT;
                            Admin::script($script_three);
                    $chengjiao=crm_deal::where("deal_orderid",$id)->first();
                    if($chengjiao){
                            $tab->add('成交单详情', $this->xiangqing($chengjiao->id));
                            $tab->add('游客详情', $this->lkxiangqing($chengjiao->id));
                            $script_addones=<<<EOT
                            $('form input').attr("disabled",true);
                            $('form select').attr("disabled",true);
                            $('form textarea').attr("disabled",true);
                            $(":submit").parent().parent().parent().css("display","none");
                            $(".nav-tabs").children().eq(1).removeClass("active");
                            $(".nav-tabs").children().eq(1).children().attr("aria-expanded","false");
                            $(".nav-tabs").children().eq(4).addClass("active");
                            $(".nav-tabs").children().eq(4).children().attr("aria-expanded","true");
                            $(".tab-content").children().eq(1).attr("class","tab-pane");
                            $(".tab-content").children().eq(4).attr("class","tab-pane active");

EOT;
                            Admin::script($script_addones);
                            $youke=crm_tourist::where("deal_id",$chengjiao->id)->first();
                            if($youke){
                                $tab->add('收款记录',$this->shoukuan($chengjiao->id));
                                $tab->add('请款记录',$this->qingkuan($chengjiao->id));
                                $tab->add('回访记录',$this->diaocha($chengjiao->id));
                                $script_addones=<<<EOT
                                $(".nav-tabs").children().eq(4).removeClass("active");
                                $(".nav-tabs").children().eq(4).children().attr("aria-expanded","false");
                                $(".nav-tabs").children().eq(5).addClass("active");
                                $(".nav-tabs").children().eq(5).children().attr("aria-expanded","true");
                                $(".tab-content").children().eq(4).attr("class","tab-pane");
                                $(".tab-content").children().eq(5).attr("class","tab-pane active");
                                $("form:eq(3) input").attr("disabled",false);
                                $("form:eq(3) select").attr("disabled",false);
                                $("form:eq(4) input").attr("disabled",false);
                                $("form:eq(4) select").attr("disabled",false);
                                $("form:eq(3) button:eq(0)").parent().parent().parent().css("display","block");
                                $("form:eq(4) button:eq(0)").parent().parent().parent().css("display","block");
EOT;
                            Admin::script($script_addones);

                            }
                    }else{
                        if($list->order_statue==4){
                            $tab->add('录入成交单', $this->chengjiao($id));
                            $script_addones=<<<EOT
                            $(".nav-tabs").children().eq(1).removeClass("active");
                            $(".nav-tabs").children().eq(1).children().attr("aria-expanded","false");
                            $(".nav-tabs").children().eq(3).addClass("active");
                            $(".nav-tabs").children().eq(3).children().attr("aria-expanded","true");
                            $(".tab-content").children().eq(1).attr("class","tab-pane");
                            $(".tab-content").children().eq(3).attr("class","tab-pane active");

EOT;
                            Admin::script($script_addones);
                        }elseif($list->order_statue==3){
                            $script_addones=<<<EOT
                            $(".box-footer").css("display","none");
                            $('form input').attr("disabled",true);
                            $('form select').attr("disabled",true);
                            $('form textarea').attr("disabled",true);

EOT;
                            Admin::script($script_addones);
                        }else{
                            $script_addones=<<<EOT
                            $(".nav-tabs").children().eq(1).removeClass("active");
                            $(".nav-tabs").children().eq(1).children().attr("aria-expanded","false");
                            $(".nav-tabs").children().eq(2).addClass("active");
                            $(".nav-tabs").children().eq(2).children().attr("aria-expanded","true");
                            $(".tab-content").children().eq(1).attr("class","tab-pane");
                            $(".tab-content").children().eq(2).attr("class","tab-pane active");

EOT;
                            Admin::script($script_addones);
                        }
                    }

                    
                    $column->append($tab);
                });
            });
        });
    }

    
    // 添加跟单调用界面
    public function create($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('跟单记录');
            $content->description('下次跟单');
            $form=new Form();
            $form->action(admin_url('crm_order/hfstore/'.$id));
            $form->date("date","跟单时间");
            $form->hidden("order_id","工单ID")->default($id);
            $form->hidden("user_id","员工ID")->default(Admin::user()->id);
            $content->body($form);
        });
    }
    // 执行添加
    public function hfstore(Request $request,$id)
    {
        //前端验证不得为空
        $list=$request->except("_token");
        $rule=[
            'date'=>'required',
        ];
        $mess=[
            'date.required'=>'跟单时间必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $res=crm_huifang::create($list);
            if($res){
                $success = new MessageBag([
                    'title'   => '添加成功',
                ]);
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '添加失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }   
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(crm_order::class, function (Grid $grid) {
            if(Admin::user()->isAdministrator()){
                $grid->model()->orderBy('id', 'desc');
            }else{
                $grid->model()->where('staff_id', Admin::user()->id)->orderBy('id', 'desc');
            }
            $grid->id('序号')->sortable();
            $grid->crm_customer()->customer_name('客户姓名');
            $grid->column('crm_route1.title','旅游类型');
            $grid->column('crm_route2.title','旅游地点');
            $grid->crm_biaoqian()->name('旅游标签');
            $grid->order_lvyoudate('旅游日期');
            $grid->admin_users()->username('员工姓名');
            $grid->order_orderdate('录入时间');
            $list=['1'=>'商谈','2'=>'进行','3'=>'失败','4'=>'成功'];
            $grid->column('order_statue','工单状态')->display(function ($order_statue) use ($list) {
                return $list[$order_statue];
            });
            $grid->disableCreation();
            $grid->tools(function ($tools) {
                $tools->append(new XiadanGender());
            });
            $grid->disableExport();//禁用导出按钮
            $grid->disableRowSelector();//禁用行选择
            $grid->actions(function ($actions) {
                $actions->disableDelete();//禁用删除
                $actions->disableEdit();//禁用编辑
                $actions->append('<a href="'.admin_url('crm_order').'/'.$actions->getKey().'/edit'.'" class="btn btn-sm btn-primary">查看详情</a>');
            });
            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('crm_customer', function ($query) use ($input) {
                        $query->where('customer_name', 'like', "%{$input}%");
                    });
                }, '客户姓名');
                $list=crm_route::where("parent_id",0)->pluck("title","id");
                $list2=crm_route::where("parent_id","!=",0)->pluck("title","id");
                $list3=crm_biaoqian::all()->pluck("name","id");
                $list4=['1'=>'商谈','2'=>'进行','3'=>'失败','4'=>'成功'];
                $filter->equal('order_didian','旅游类型')->select($list);
                $filter->equal('order_didian2','旅游地点')->select($list2);
                $filter->equal('order_lvyouleibie','标签')->select($list3);
                $filter->between('order_lvyoudate', '旅游日期')->datetime();
                $filter->equal('order_statue','状态')->select($list4);
            });
            $script_addones=<<<EOT
                
                $(".order_didian").change(function(){
                    var id=$(".order_didian option:selected").val();
                    $.ajax({
                        url: "/admin/gdindex/ajax5",
                        type: "get",
                        dataType: "json",
                        data: {'v': id},
                        success:function(data){
                            var hh="<option value>请-选-择<\/option>";
                            for(var i=0;i<data.length;i++){
                                hh +="<option value="
                                hh +=data[i].id
                                hh +=" >"
                                hh +=data[i].title
                                hh +="<\/option>";
                                // document.getElementsByClassName('order_didian2').options[i] = new Option(data[i].title,data[i].id);
                            }
                            $(".order_didian2").html(hh).parent().parent().css("display","block");;
                        }
                    }); 
                })

EOT;
            Admin::script($script_addones);
        });
    }

    // 客户详情表单
    protected function kehu($id)
    {
        $list=crm_customer::find($id);
        $form=new Form($list);
        $form->select('customer_laiyuan','客户来源')->options(['1'=>'网站','2'=>'转介绍','3'=>'上门','4'=>'电话销售','5'=>'老客户','6'=>'其他'])->attribute(['disabled' => true]);
        $form->text('customer_name', '客户姓名')->attribute(['disabled' => true]);
        $form->text('customer_age', '客户年龄')->attribute(['disabled' => true]);
        $form->select('customer_sex', '性别')->options(['1'=>'男','2'=>'女'])->attribute(['disabled' => true]);
        $form->mobile('customer_phone', '客户电话')->options(['mask' => '999 9999 9999'])->attribute(['disabled' => true]);
        $form->text('customer_weixin', '微信')->attribute(['disabled' => true]);
        $form->text('customer_qq', 'QQ')->attribute(['disabled' => true]);
        $form->email('customer_email','邮箱Email')->attribute(['disabled' => true]);
        $form->text('customer_sfz','身份证号码')->attribute(['disabled' => true]);
        $form->select('customer_type','客户类别')->options(['单位'=>'单位','个人'=>'个人'])->attribute(['disabled' => true]);
        $form->text('customer_danwei', '单位')->attribute(['disabled' => true]);
        $res=Admin_users::all()->pluck('username','id');
        $form->select('customer_kaifa','开发人')->options($res)->attribute(['disabled' => true]);
        $form->date('customer_kfdate','开发时间')->attribute(['disabled' => true]);
        $form->select('customer_weihu','维护人')->options($res)->attribute(['disabled' => true]);
        $form->textarea('customer_beizhu','工单备注')->rows(3)->attribute(['disabled' => true]);
        return  $form->render();
    }
    // 工单详情
    protected function gongdan($id)
    {
        $list=crm_order::find($id);
        $form=new Form($list);
        $form->action(admin_url('crm_order/gdxiugai')."/".$id);
        $list=crm_order::find($id)->crm_route1;
        $res=crm_route::where("parent_id",$list->parent_id)->get()->pluck("title","id");
        $form->select('order_didian','旅游类型')->options($res);
        $list2=crm_order::find($id)->crm_route2;
        $res2=crm_route::where("parent_id",$list2->parent_id)->get()->pluck("title","id");
        $form->select('order_didian2', '旅游地点')->options($res2);
        $form->text('order_xianlu','旅游线路');
        $biaoqian=crm_biaoqian::all()->pluck("name","id");
        $form->select('order_lvyouleibie','标签')->options($biaoqian);
        $form->date('order_lvyoudate', '出发时间');
        $form->textarea('order_beizhu','工单备注')->rows(3);
        $zhuangtai=['1'=>'商谈','2'=>'进行','3'=>'失败','4'=>'成功'];
        $form->select('order_statue','工单状态')->options($zhuangtai);
        $form->textarea('order_yuanyin',"失败原因");
        $staff=Admin_users::all()->pluck('username','id');
        $form->select('staff_id','录入人')->options($staff)->attribute(['disabled' => true]);
        $script_addones=<<<EOT
                var statue=$(".order_statue option:selected").val();
                if(statue==3){
                    $("textarea[name='order_yuanyin']").parent().parent().css("display","block");
                }else{
                    $("textarea[name='order_yuanyin']").parent().parent().css("display","none");
                }
                $(".nav-tabs").children().eq(0).removeClass("active");
                $(".nav-tabs").children().eq(0).children().attr("aria-expanded","false");
                $(".nav-tabs").children().eq(1).addClass("active");
                $(".nav-tabs").children().eq(1).children().attr("aria-expanded","true");
                $(".tab-content").children().eq(0).attr("class","tab-pane");
                $(".tab-content").children().eq(1).attr("class","tab-pane active");
                $(".order_didian").change(function(){
                    var id=$(".order_didian option:selected").val();
                    $.ajax({
                        url: "/admin/gdindex/ajax5",
                        type: "get",
                        dataType: "json",
                        data: {'v': id},
                        success:function(data){
                            var hh="<option value=\"请-选-择\">请-选-择<\/option>";
                            for(var i=0;i<data.length;i++){
                                hh +="<option value="
                                hh +=data[i].id
                                hh +=" >"
                                hh +=data[i].title
                                hh +="<\/option>";
                                // document.getElementsByClassName('order_didian2').options[i] = new Option(data[i].title,data[i].id);
                            }
                            $(".order_didian2").html(hh).parent().parent().css("display","block");;
                        }
                    }); 
                })
                $(".order_statue").change(function(){
                    var id=$(".order_statue option:selected").val();
                    if(id==3){
                        $("textarea[name='order_yuanyin']").parent().parent().css("display","block");
                    }else{
                        $("textarea[name='order_yuanyin']").parent().parent().css("display","none");
                    }
                })

EOT;
            Admin::script($script_addones);
        return  $form->render();
    }
    // 工单修改
    protected function gdxiugai(Request $request , $id)
    {
        //前端验证不得为空
        $list=$request->except("_token");
        $rule=[
            'order_didian'=>'required',
            'order_didian2'=>'required',
            'order_xianlu'=>'required',
            'order_lvyouleibie'=>'required',
            'order_lvyoudate'=>'required',
            'order_beizhu'=>'required',
            'order_statue'=>'required',
        ];
        $mess=[
            'order_didian.required'=>'旅游类型必须输入',
            'order_didian2.required'=>'旅游地点必须输入',
            'order_xianlu.required'=>'旅游线路必须输入',
            'order_lvyouleibie.required'=>'旅游标签必须输入',
            'order_lvyoudate.required'=>'旅游时间必须输入',
            'order_beizhu.required'=>'工单备注必须输入',
            'order_statue.required'=>'工单状态必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行修改
            $gd=crm_order::find($id);
            $gd->order_didian=$list['order_didian'];
            $gd->order_didian2=$list['order_didian2'];
            $gd->order_xianlu=$list['order_xianlu'];
            $gd->order_lvyouleibie=$list['order_lvyouleibie'];
            $gd->order_lvyoudate=$list['order_lvyoudate'];
            $gd->order_beizhu=$list['order_beizhu'];
            $gd->order_statue=$list['order_statue'];
            $gd->order_yuanyin=$list['order_yuanyin'];
            $gd->staff_id=Admin::user()->id;
            $res=$gd->save();
            if($list['order_statue']==4){
                $huifang=\DB::table("crm_huifang")->where("order_id",$gd->id)->where("statue",1)->delete();
            }
            if($res){
                $success = new MessageBag([
                    'title'   => '修改成功',
                ]);
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '修改失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }   
    }
    // 录入成交单
    protected function chengjiao($id)
    {
        $form= new Form();
        $form->action(admin_url('crm_order/cjtianjia').'/'.$id);
        $form->select('deal_hetongtype','合同类型')->options(crm_hetongtype::all()->pluck('title','title'));
        $hetong=crm_hetong::where('statue',2)->where('type',crm_hetongtype::all()->first()->pluck('id')[0])->where('users_id',Admin::user()->username)->get()->pluck('hetong','hetong');
        $form->select('deal_hetong','合同编号')->options($hetong);
        $form->number('deal_num', '旅游人数');
        $form->currency('deal_yshoukuan','应收款')->symbol('￥');
        $form->currency('deal_ydakuan','应付款')->symbol('￥');
        $form->select('deal_leibie','操作类别')->options(['外拼'=>'外拼','自组'=>'自组']);
        $list=crm_supplier::all()->pluck("supplier_name","id");
        $form->multipleSelect('deal_gongyingshang','供应商名称')->options($list);
        $form->date('deal_ftdate', '出发时间')->format('YYYY-MM-DD');
        $form->hidden('deal_dealdate','单子产生时间')->default(date("y-m-d h:i:s"));
        $form->hidden('deal_jiesuanstatue','结算状态')->default(1);
        $form->hidden('deal_orderid','工单id')->default($id);
        $customer=crm_order::find($id)->order_customerid;
        $form->hidden('deal_customer_id','客户id')->default($customer);
        $form->hidden('deal_yuangong','员工姓名')->default(Admin::user()->username);
        $form->hidden('deal_sshoukuan','实收款')->default(0);
        $form->hidden('deal_sdakuan','实请款')->default(0);
        $form->hidden('deal_lirun','实际毛利')->default(0);
        $form->hidden('deal_userid','员工ID')->default(Admin::user()->id);
        $script_addones=<<<EOT
                $(".deal_hetongtype").change(function(){
                    var id=$(".deal_hetongtype option:selected").val();
                    $.ajax({
                        url: "/admin/gdindex/ajax8",
                        type: "get",
                        dataType: "json",
                        data: {'v': id},
                        success:function(data){
                            var hh="<option value=\"请选择\">请选择<\/option>";
                            for(var i=0;i<data.length;i++){
                                hh +="<option value="
                                hh +=data[i]
                                hh +=" >"
                                hh +=data[i]
                                hh +="<\/option>";
                            }
                            $(".deal_hetong").html(hh);
                        }
                    }); 
                })

EOT;
        Admin::script($script_addones);
        return $form->render();
    }
    // 成交单添加
    public function cjtianjia(Request $request,$id)
    {
        //前端验证不得为空
        $list2=$request->deal_gongyingshang;
        $list=$request->except("_token");

        if($list['deal_num']==0){
                $error = new MessageBag([
                    'title'   => '旅游人数不得为零',
                ]);
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('error'));
        }
        if($list['deal_leibie']=="外拼" && empty($list['deal_gongyingshang'][0])){
                $error = new MessageBag([
                    'title'   => '供应商不得为空',
                ]);
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('error'));
        }
        $list=$request->except("_token","deal_gongyingshang");
        $rule=[
            'deal_hetong'=>'required',
            'deal_yshoukuan'=>'required',
            'deal_ydakuan'=>'required',
            'deal_ftdate'=>'required',
            'deal_num'=>'required',
        ];
        $mess=[
            'deal_hetong.required'=>'合同编号必须输入',
            'deal_yshoukuan.required'=>'应收款必须输入',
            'deal_ydakuan.required'=>'应打款必须输入',
            'deal_ftdate.required'=>'出发时间必须输入',
            'deal_num.required'=>'旅游人数必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $list['deal_yglirun']=$list['deal_yshoukuan']-$list['deal_ydakuan'];
            $res=\DB::table('crm_deal')->insertGetid($list);
            $hetong=crm_hetong::where('type',crm_hetongtype::all()->where('title',$list['deal_hetongtype'])->pluck('id')[0])->first();
            $hetong->deal_id=$res;
            $hetong->customer_id=$list['deal_customer_id'];
            $hetong->statue=3;
            $hetong->save();
            if($res){
                foreach($list2 as $value){
                    if($value){
                        $ll=['crm_deal_id'=>$res,'crm_supplier_id'=>$value];
                        $aa=\DB::table('crm_deal_crm_supplier')->insertGetid($ll);
                    }
                }
                $success = new MessageBag([
                    'title'   => '下单成功',
                ]);
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '下单失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }

    }
    // 成交单详情
    public function xiangqing($id)
    {
        $list=crm_deal::find($id);
        $form=new Form($list);
        $form->action(admin_url('crm_order/cjxiugai/'.$id));
        $form->select('deal_hetongtype','合同类型')->options(crm_hetongtype::all()->pluck('title','title'));
        $hetong=crm_hetong::where('type',crm_hetongtype::all()->where('title',$list['deal_hetongtype'])->pluck('id')[0])->where('users_id',Admin::user()->username)->get()->pluck('hetong','hetong');
        $form->select('deal_hetong','合同编号')->options($hetong);
        $form->number('deal_num', '旅游人数');
        $form->currency('deal_yshoukuan','应收款')->symbol('￥');
        $form->currency('deal_ydakuan','应付款')->symbol('￥');
        $form->currency('deal_yglirun','预估毛利')->symbol('￥');
        $form->currency('deal_sshoukuan','实收款')->symbol('￥');
        $form->currency('deal_sdakuan','实付款')->symbol('￥');
        $form->currency('deal_lirun','实际毛利')->symbol('￥');
        $form->select('deal_leibie','操作类别')->options(['外拼'=>'外拼','自组'=>'自组']);
        $list2=crm_supplier::all()->pluck("supplier_name","id");
        $form->multipleSelect('crm_suppliers->id','供应商名称')->options($list2);
        $form->datetime('deal_ftdate', '出发时间');
        $form->text('deal_yuangong', '员工姓名');
        $jiesuan=['1'=>'未结算','2'=>'正在结算','3'=>'已核算'];
        $form->select('deal_jiesuanstatue','结算状态')->options($jiesuan);
        return $form->render();
    }
    // 成交单修改
    public function cjxiugai(Request $request,$id)
    {
        //前端验证不得为空
        $list=$request->except("_token");
        $rule=[
            'deal_num'=>'required',
            'deal_yshoukuan'=>'required',
            'deal_ydakuan'=>'required',
            'deal_leibie'=>'required',
            'deal_dkfs'=>'required',
            'deal_ftdate'=>'required',
        ];
        $mess=[
            'deal_num.required'=>'旅游人数必须输入',
            'deal_yshoukuan.required'=>'应收款必须输入',
            'deal_ydakuan.required'=>'应打款必须输入',
            'deal_leibie.required'=>'操作类别必须输入',
            'deal_dkfs.required'=>'打款方式必须输入',
            'deal_ftdate.required'=>'发团日期必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行修改
            $gd=crm_deal::find($id);
            $gd->deal_num=$list['deal_num'];
            $gd->deal_yshoukuan=$list['deal_yshoukuan'];
            $gd->deal_ydakuan=$list['deal_ydakuan'];
            $gd->deal_leibie=$list['deal_leibie'];
            $gd->deal_dkfs=$list['deal_dkfs'];
            $gd->deal_ftdate=$list['deal_ftdate'];
            $gd->deal_gongyingshang=$list['deal_gongyingshang'];
            $res=$gd->save();
            if($res){
                $success = new MessageBag([
                    'title'   => '修改成功',
                ]);
                return redirect(admin_url('crm_order/'.$gd->deal_orderid.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '修改失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }   
    }
    // 跟单表格
    public function huifang($id)
    {
        return Admin::grid(crm_huifang::class, function (Grid $grid) use ($id) {
            $grid->model()->where('order_id', $id);
            $list=crm_order::find($id);
            // $grid->id("序号");
            $grid->column('客户姓名')->display(function () use ($list) {
                return $list->crm_customer->customer_name;
            });
            $grid->column('线路')->display(function () use ($list) {
                return $list->order_xianlu;
            });
            $grid->column('标签')->display(function () use ($list) {
                return $list->crm_biaoqian->name;
            });
            $grid->date("跟单时间");
            $zhuangtai=['1'=>'未跟单','2'=>'已跟单'];
            $grid->statue('状态')->display(function ($statue) use ($zhuangtai) {
                return $zhuangtai[$statue];
            });
            // $grid->statue("状态");
            $grid->actions(function ($actions) {
                $actions->disableDelete();//禁用删除按钮
                $actions->disableEdit();//禁用编辑按钮
                if($actions->row->statue=="2"){
                    $actions->append('
                        <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#myModal'.$actions->getKey().'">查看备注</button>
                        <div class="modal fade" id="myModal'.$actions->getKey().'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                          <div class="modal-dialog" role="document">
                            <div class="modal-content">
                              <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title" id="myModalLabel">跟单备注</h4>
                              </div>
                              <div class="modal-body">
                                    <div class="form">
                                        <div class="form-group">
                                        备注：<textarea name="content" id="" style="resize:none;width:100%;margin:0 auto;height:200px;">'.$actions->row->content.'</textarea>
                                        </div>
                                    </div>
                              </div>
                            </div>
                          </div>
                        </div>
                        ');
                }else{
                    $actions->append('
                        <button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#hfModal'.$actions->getKey().'">添加备注</button>
                        <div class="modal fade" id="hfModal'.$actions->getKey().'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                          <div class="modal-dialog" role="document">
                            <div class="modal-content">
                              <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title" id="myModalLabel">跟单备注</h4>
                              </div>
                              <div class="modal-body">
                                    <form action="'.admin_url('crm_order/hfbeizhu').'/'.$actions->getKey().'" id="huifangform" method="post">
                                   '. csrf_field() .'
                                    <div class="form">
                                        <div class="form-group">
                                        备注：<textarea name="content" id="" style="resize:none;width:100%;margin:0 auto;height:200px;"></textarea>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="submit" id="huifangtype" class="btn btn-primary submit">提交</button>
                                            <button type="reset" class="btn btn-warning pull-left">撤销</button>
                                        </div>
                                    </div>
                                    </form>
                              </div>
                              
                            </div>
                          </div>
                        </div>
                        ');
                }
            });
            $deal=crm_deal::where('deal_orderid',$id)->first();
            $oo=crm_order::where('id',$id)->first();
            if($deal || $oo->order_statue==3){
                $grid->disableCreation();//禁用创建按钮
            }
            $grid->disableFilter();//禁用查询过滤器
            $grid->disableExport();//禁用导出按钮
            $grid->disableRowSelector();//禁用行选择
        });
    }
    // 跟单备注填写
    public function hfbeizhu(Request $request,$id)
    {
        $list=$request->except("_token");
        $rule=[
            'content'=>'required',
        ];
        $mess=[
            'content.required'=>'跟单备注必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行修改
            $gd=crm_huifang::find($id);
            $gd->content=$list['content'];
            $gd->statue=2;
            $res=$gd->save();
            if($res){
                $success = new MessageBag([
                    'title'   => '跟单成功',
                ]);
                $hf=crm_huifang::find($id)->order_id;
                return redirect(admin_url('crm_order/'.$hf.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '跟单失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }   

    }
    // 收款记录表
    public function shoukuan($id)
    {
        return Admin::grid(crm_receive::class, function (Grid $grid) use ($id) {
            $grid->model()->where('receive_dealid', $id);
            $list=crm_deal::find($id);
            $grid->id("序号");
            
            $grid->column('客户')->display(function () use ($list) {
                return crm_customer::find(crm_order::find($list->deal_orderid)->order_customerid)->customer_name;
            });
            $grid->column('电话')->display(function () use ($list) {
                return crm_customer::find(crm_order::find($list->deal_orderid)->order_customerid)->customer_phone;
            });
            $grid->column('线路名称')->display(function () use ($list) {
                return crm_order::find($list->deal_orderid)->order_xianlu;
            });
            $grid->column('出发日期')->display(function () use ($list) {
                return $list->deal_ftdate;
            });
            $grid->receive_yuangong("员工姓名");
            $grid->crm_account()->account_type("收款方式");
            $grid->receive_date("收款日期");
            $grid->receive_sshoukuan("收款金额");
            $zhuangtai=['1'=>'审批中','2'=>'通过','3'=>'驳回'];
            $grid->receive_statue('收款状态')->display(function ($receive_statue) use ($zhuangtai) {
                return $zhuangtai[$receive_statue];
            });
            if($list->deal_sshoukuan){
                if($list->deal_jiesuanstatue==1){
                    $grid->tools(function ($tools) use ($list) {
                        $tools->append(new ShoukuanGender());
                        $tools->append(new HesuanGender());
                    });
                }elseif($list->deal_jiesuanstatue==2){
                    if(Admin::user()->isRole('caiwu') || Admin::user()->isRole('administrator') ){
                        $grid->tools(function ($tools) use ($list) {
                            $tools->append(new CwhesuanGender());
                        });
                    }else{
                        $grid->tools(function ($tools) use ($list) {
                            $tools->append(new JxhesuanGender());
                        });
                    }
                
                }else{
                    $grid->tools(function ($tools) use ($list) {
                        $tools->append(new YhesuanGender());
                    });
                }
            }else{
                $grid->tools(function ($tools) use ($list) {
                        $tools->append(new ShoukuanGender());
                    });
            }
            $url=json_encode(admin_url('crm_order/skcreate/'.$id));
            $hsurl=json_encode(admin_url('crm_order/hesuan/'.$id));
            $cwurl=json_encode(admin_url('crm_order/cwhesuan/'.$id));
            $script_addones=<<<EOT
                $("#shoukuan").attr("href",$url);
                $("#hesuan").attr("href",$hsurl);
                $("#cwhesuan").attr("href",$cwurl);

EOT;
            Admin::script($script_addones);
            $grid->disableCreation();//禁用创建按钮
            $grid->disableFilter();//禁用查询过滤器
            $grid->disableExport();//禁用导出按钮
            $grid->disableRowSelector();//禁用行选择
            $grid->actions(function ($actions) {
                $actions->disableDelete();//禁用删除按钮
                $actions->disableEdit();//禁用编辑按钮
                    $actions->append('
                    <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#skModal">查看详情</button>
                    <div class="modal fade" id="skModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                      <div class="modal-dialog" role="document">
                        <div class="modal-content">
                          <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">收款备注</h4>
                          </div>
                          <div class="modal-body">
                                <div class="form">
                                    <div class="form-group">
                                    收款人：<input type="text" value="'.crm_receive::find($actions->getKey())->crm_account->account_name.'">
                                    </div>
                                    <div class="form-group">
                                    收款方式：<input type="text" value="'.crm_receive::find($actions->getKey())->crm_account->account_type.'">
                                    </div>
                                    <div class="form-group">
                                    收款账号：<input type="text" value="'.crm_receive::find($actions->getKey())->crm_account->account_number.'">
                                    </div>
                                    <div class="form-group" style="width:200px;">
                                    上传凭证：<img  id="ima" src="'.asset("uploads/img").'/'.$actions->row->receive_ima.'"style="width:100%" alt="">
                                    </div>
                                    <div class="form-group">
                                    收款备注：<textarea name="sk" id="sk" style="resize:none;width:100%;margin:0 auto;height:200px;" >'.$actions->row->receive_beizhu.'</textarea>
                                    </div>
                                </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    ');
                
            });
            $script_addones=<<<EOT
                $("#ima").mouseover(function(){
                  $("#ima").parent().animate({
                    left:'250px',
                    width:'100%'
                  });
                });
                $("#ima").mouseout(function(){
                  $("#ima").parent().animate({
                    left:'0px',
                    width:'200px'
                  });
                });
EOT;
            Admin::script($script_addones);
        });
    }
    // 收款单填写
    public function skcreate($id)
    {
       return Admin::content(function (Content $content) use ($id) {
            $content->header('收款管理');
            $content->description('添加');
            $form=new Form();
            $res=crm_deal::find($id)->deal_orderid;
            $form->action(admin_url('crm_order/sktianjia/'.$res));
            $list=crm_account::all()->pluck('account_type','id');
            $form->select('receive_type', '账户类别')->options($list);
            $zhanghu=crm_account::first()->account_number;
            $form->text('receive_zhanghao', '账户账号')->default($zhanghu);
            $form->date('receive_date','收款日期');
            $form->currency('receive_sshoukuan', '收款金额')->symbol('￥');
            $form->hidden('receive_dealid','成单ID')->default($id);
            $form->hidden('receive_orderid','工单ID')->default($res);
            $form->image('receive_ima', '上传凭证');
            $form->textarea('receive_beizhu','备注');
            $form->hidden('receive_statue','状态')->default(1);
            $form->hidden('receive_userid','员工ID')->default(Admin::user()->id);
            $form->hidden('receive_yuangong','状态')->default(Admin::user()->username);
            $script_addones=<<<EOT
                $(".receive_type").change(function(){
                    var id=$(".receive_type option:selected").val();
                    $.ajax({
                        url: "/admin/gdindex/ajax11",
                        type: "get",
                        dataType: "json",
                        data: {'v': id},
                        success:function(data){
                           $(".receive_zhanghao").val(data);
                        }
                    }); 
                })
               

EOT;
            Admin::script($script_addones);
            $content->body($form);
        });
    }
    // 收款添加
    public function sktianjia(Request $request,$id)
    {
        //前端验证不得为空
        $list=$request->except("_token");

        
        $rule=[
            'receive_zhanghao'=>'required',
            'receive_date'=>'required',
            'receive_type'=>'required',
            'receive_sshoukuan'=>'required',
            'receive_beizhu'=>'required',
        ];
        $mess=[
            'receive_zhanghao.required'=>'账号必须输入',
            'receive_date.required'=>'日期必须输入',
            'receive_type.required'=>'收款类型必须输入',
            'receive_sshoukuan.required'=>'实收款必须输入',
            'receive_beizhu.required'=>'备注必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $filedir="uploads/img/"; //2、定义图片上传路径
            $imagesName=$list['receive_ima']->getClientOriginalName(); //3、获取上传图片的文件名
            $extension =$list['receive_ima'] -> getClientOriginalExtension(); //4、获取上传图片的后缀名
            $newImagesName=md5(time()).random_int(5,5).".".$extension;//5、重新命名上传文件名字
            $list['receive_ima']->move($filedir,$newImagesName); //6、使用move方法移动文件
            $list['receive_ima']=$newImagesName;
            $res=crm_receive::create($list);
            if($res){
                $success = new MessageBag([
                    'title'   => '申请成功',
                ]);
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '申请失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }
    }
    // 请款记录表
    public function qingkuan($id)
    {
        return Admin::grid(crm_funds::class, function (Grid $grid) use ($id) {
            $grid->model()->where('funds_dealid', $id);
            $list=crm_deal::find($id);
            $grid->column('客户')->display(function () use ($list) {
                return crm_customer::find(crm_order::find($list->deal_orderid)->order_customerid)->customer_name;
            });
            $grid->column('电话')->display(function () use ($list) {
                return crm_customer::find(crm_order::find($list->deal_orderid)->order_customerid)->customer_phone;
            });
            $grid->column('线路名称')->display(function () use ($list) {
                return crm_order::find($list->deal_orderid)->order_xianlu;
            });
            $grid->column('出发日期')->display(function () use ($list) {
                return $list->deal_ftdate;
            });
            $grid->funds_name("请款人");
            $grid->crm_supplier()->supplier_name("供应商名称");
            $grid->funds_money("请款金额");
            $grid->funds_date("请款时间");
            $zhuangtai=['1'=>'审批中','2'=>'通过','3'=>'驳回'];
            $grid->funds_statue('请款状态')->display(function ($funds_statue) use ($zhuangtai) {
                return $zhuangtai[$funds_statue];
            });
            if($list->deal_jiesuanstatue==1){
                $grid->tools(function ($tools) {
                    $tools->append(new QingkuanGender());
                });
            }
            $url=json_encode(admin_url('crm_order/qkcreate/'.$id));
            $script_addones=<<<EOT
                $("#qingkuan").attr("href",$url);

EOT;
            Admin::script($script_addones);
            $grid->disableCreation();//禁用创建按钮
            $grid->disableFilter();//禁用查询过滤器
            $grid->disableExport();//禁用导出按钮
            $grid->disableRowSelector();//禁用行选择
            $grid->actions(function ($actions) {
                $actions->disableDelete();//禁用删除按钮
                $actions->disableEdit();//禁用编辑按钮
                $actions->append('
                    <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#qkModal">查看详情</button>
                    <div class="modal fade" id="qkModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                      <div class="modal-dialog" role="document">
                        <div class="modal-content">
                          <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">请款详情</h4>
                          </div>
                          <div class="modal-body">
                                <div class="form">
                                    <div class="form-group">
                                    请款人：<input type="text" value="'.$actions->row->funds_name.'">
                                    </div>
                                    <div class="form-group">
                                    供应商名称：<input type="text" value="'.crm_supplier::where('id',$actions->row->funds_gongyingshang)->first()->supplier_name.'">
                                    </div>
                                    <div class="form-group">
                                    请款方式：<input type="text" value="'.supplier_type::where('id',$actions->row->funds_zhtype)->first()->typename.'">
                                    </div>
                                    <div class="form-group">
                                    请款账号：<input type="text" value="'.$actions->row->funds_zhanghu.'">
                                    </div>
                                    <div class="form-group" style="width:200px;">
                                    上传凭证：<img  id="funds" src="'.asset("uploads/img").'/'.$actions->row->funds_ima.'"style="width:100%" alt="">
                                    </div>
                                    <div class="form-group">
                                    请款备注：<textarea name="beizhu" id="qk" style="resize:none;width:100%;margin:0 auto;height:100px;">'.$actions->row->funds_beizhu.'</textarea>
                                    </div>
                                </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    ');  
                
            });
            $script_addones=<<<EOT
                $("#funds").mouseover(function(){
                  $("#funds").parent().animate({
                    left:'250px',
                    width:'100%'
                  });
                });
                $("#funds").mouseout(function(){
                  $("#funds").parent().animate({
                    left:'0px',
                    width:'200px'
                  });
                });
EOT;
            Admin::script($script_addones);
        });
    }
    // 请款记录填写
    public function qkcreate($id)
    {
       return Admin::content(function (Content $content) use ($id) {
            $content->header('请款管理');
            $content->description('添加');
            $form=new Form();
            $res=crm_deal::find($id)->deal_orderid;
            $form->action(admin_url('crm_order/qktianjia/'.$res));
            $sup=\DB::table("crm_deal_crm_supplier")->where("crm_deal_id",$id)->pluck("crm_supplier_id");
            $list=crm_supplier::whereIn("id",$sup)->pluck('supplier_name','id');
            $form->select('funds_gongyingshang', '账号名称')->options($list);
            $type=supplier_type::where('supplier_id',crm_supplier::first()->id)->get()->pluck('typename','id');
            $form->select('funds_zhtype','账号类别')->options($type);
            $zhanghao=supplier_type::where('supplier_id',crm_supplier::first()->id)->first()->zhanghao;
            $form->text('funds_zhanghao','账号')->default($zhanghao)->attribute(['disabled' => 'disabled']);
            $form->currency('funds_money', '请款金额')->symbol('￥');
            $form->image('funds_ima', '上传凭证');
            $form->textarea('funds_beizhu','备注');
            $form->hidden('funds_dealid','成单ID')->default($id);
            $form->hidden('funds_orderid','工单ID')->default($res);
            $form->hidden('funds_userid','员工ID')->default(Admin::user()->id);
            $form->hidden('funds_date','请款时间')->default(date("y-m-d h:i:s"));
            $form->hidden('funds_name','请款人姓名')->default(Admin::user()->username);
            $script_addones=<<<EOT
                $(".funds_gongyingshang").change(function(){
                    var id=$(".funds_gongyingshang option:selected").val();
                    $.ajax({
                        url: "/admin/gdindex/ajax6",
                        type: "get",
                        dataType: "json",
                        data: {'v': id},
                        success:function(data){
                            var hh="<option value=\"请选择\">请选择<\/option>";
                            for(var i=0;i<data.length;i++){
                                hh +="<option value="
                                hh +=data[i].id
                                hh +=" >"
                                hh +=data[i].typename
                                hh +="<\/option>";
                            }
                            $(".funds_zhtype").html(hh);
                            $(".funds_zhanghao").parent().parent().parent().css("display","none");
                        }
                    }); 
                })
                $(".funds_zhtype").change(function(){
                    var id=$(".funds_zhtype option:selected").val();
                    $.ajax({
                        url: "/admin/gdindex/ajax7",
                        type: "get",
                        dataType: "json",
                        data: {'v': id},
                        success:function(data){
                            $(".funds_zhanghao").val(data);
                            $(".funds_zhanghao").parent().parent().parent().css("display","block");
                        }
                    }); 
                })

EOT;
            Admin::script($script_addones);
            $content->body($form);
        });
    }
    // 请款添加
    public function qktianjia(Request $request,$id)
    {
        //前端验证不得为空
        $list=$request->except("_token");
        $rule=[
            'funds_gongyingshang'=>'required',
            'funds_zhtype'=>'required',
            'funds_money'=>'required',
            'funds_beizhu'=>'required',
        ];
        $mess=[
            'funds_gongyingshang.required'=>'供应商名称必须输入',
            'funds_zhtype.required'=>'账户类别必须输入',
            'funds_money.required'=>'请款金额必须输入',
            'funds_beizhu.required'=>'备注必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $filedir="uploads/img/"; //2、定义图片上传路径
            $imagesName=$list['funds_ima']->getClientOriginalName(); //3、获取上传图片的文件名
            $extension =$list['funds_ima'] -> getClientOriginalExtension(); //4、获取上传图片的后缀名
            $newImagesName=md5(time()).random_int(5,5).".".$extension;//5、重新命名上传文件名字
            $list['funds_ima']->move($filedir,$newImagesName); //6、使用move方法移动文件
            $list['funds_ima']=$newImagesName;
            $zhanghao=\DB::table("supplier_type")->where("id","=",$list['funds_zhtype'])->first()->zhanghao;
            $list['funds_zhanghu']=$zhanghao;
            $li=crm_deal::find($list['funds_dealid'])->deal_sshoukuan;
            if($list['funds_money'] > $li){
                $list['funds_dianzi']=2;
            }else{
                $list['funds_dianzi']=1;
            }
            $res=crm_funds::create($list);
            if($res){
                $lirun=crm_deal::find($list['funds_dealid'])->deal_sshoukuan;
                if($list['funds_money'] > $lirun){
                     $success = new MessageBag([
                        'title'   => '此订单 需垫资，请等待总经理审批！！！',
                    ]);
                }else{
                    $success = new MessageBag([
                        'title'   => '申请成功',
                    ]);
                }
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '申请失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }
    }
    // 申请核算
    public function hesuan($id)
    {
        $list=crm_deal::find($id);
        $list->deal_jiesuanstatue=2;
        $res=$list->save();
        if($res){
            $success = new MessageBag([
                'title'   => '正在进行核算中，敬请等待！',
            ]);
            return redirect(admin_url('crm_order/'.$list->deal_orderid.'/edit'))->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title'   => '申请核算失败！',
            ]);
            return back()->with(compact('error'));    
        }
    }
    // 财务核算
    public function cwhesuan($id)
    {
        $list=crm_deal::find($id);
        $list->deal_jiesuanstatue=3;
        $list->deal_jsxiaoxi=2;
        $list->deal_jiesuandate=date("y-m");
        $res=$list->save();
        $hetong=crm_hetong::where('type',crm_hetongtype::where('title',$list['deal_hetongtype'])->pluck('id')[0])->where('hetong',$list['deal_hetong'])->first();
        $hetong->statue=3;
        $hetong->save();
        if($res){
            $success = new MessageBag([
                'title'   => '核算完毕！ 再见！',
            ]);
            return redirect(admin_url('crm_order/'.$list->deal_orderid.'/edit'))->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title'   => '核算失败！',
            ]);
            return back()->with(compact('error'));    
        }
    }
    // 旅客详情表格
    public function lkxiangqing($id)
    {
        return Admin::grid(crm_tourist::class, function (Grid $grid) use ($id) {
            $grid->model()->where('deal_id', $id);
            $list=crm_deal::find($id);
            $grid->tourist_name('游客姓名');
            $grid->tourist_sex('性别');
            $grid->tourist_phone('电话');
            $grid->tourist_number('身份证号码');
            if($list->deal_jiesuanstatue!==3){
                $grid->tools(function ($tools) use ($list) {
                    $tools->append(new LktianjiaGender());
                    $tools->append(new LkshangchuanGender());
                });
                $url=json_encode(admin_url('crm_order/lktianjia/'.$id));
                $action=json_encode(admin_url('crm_order/shangchuan/'.$id));
                $script_addones=<<<EOT
                $("#lktianjia").attr("href",$url);
                $("#wenjian input").attr("disabled",false);
                $("#wenjian").attr("action",$action);
                $("#wenjian :submit").parent().parent().parent().css("display","block");

EOT;
                Admin::script($script_addones); 
            }
            
            $grid->disableCreation();//禁用创建按钮
            $grid->disableFilter();//禁用查询过滤器
            $grid->disableExport();//禁用导出按钮
            $grid->disableRowSelector();//禁用行选择
            $grid->disableActions();//禁用行操作
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
            });
        });
    }
    // 旅客添加
    protected function lktianjia($id)
    {
        
        return Admin::content(function (Content $content) use ($id) {
            $content->header('游客管理');
            $content->description('添加');
            $order=crm_deal::find($id)->deal_orderid;
            $form=new Form();
            $form->action(admin_url('crm_order/lkxinzeng/'.$order));
            $form->text('tourist_name','姓名');
            $list=['男'=>'男','女'=>'女'];
            $form->select('tourist_sex','性别')->options($list);
            $form->text('tourist_phone','电话');
            $form->text('tourist_number','身份证号码');
            $form->hidden('deal_id','成交单ID')->default($id);
            $form->hidden('order_id','工单ID')->default($order);
            $kehu=crm_customer::find(crm_deal::find($id)->deal_customer_id);
            $form->hidden('tourist_type')->default($kehu->customer_type);
            $form->hidden('tourist_typename')->default($kehu->customer_danwei);
            $form->hidden('tourist_userid')->default(Admin::user()->id);
            $content->body($form);
        });
       
    }
    // 游客执行添加
    protected function lkxinzeng(Request $request,$id)
    {
        //前端验证不得为空
        $list=$request->except("_token");
        $rule=[
            'tourist_name'=>'required',
            'tourist_sex'=>'required',
            'tourist_phone'=>'required',
            'tourist_number'=>'required',
        ];
        $mess=[
            'tourist_name.required'=>'姓名必须输入',
            'tourist_sex.required'=>'性别必须输入',
            'tourist_phone.required'=>'电话必须输入',
            'tourist_number.required'=>'身份证号码必须输入',
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $res=crm_tourist::create($list);
            if($res){
                $success = new MessageBag([
                    'title'   => '添加成功',
                ]);
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '申请失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }
    }
    // 游客信息文件上传
    public function shangchuan(Request $request,$id)
    {
        // 文件是否上传成功
        if($request->isMethod('post')){
            $all = $request->all();
            $rules = [
                'file'=>'required',
            ];
            $messages = [
                'file.required'=>'请选择要上传的文件'
            ];
            $validator = Validator::make($all,$rules,$messages);
            if($validator->fails()){
                return back()->withErrors($validator);
            }
            //获取上传文件的大小
            $size = $request->file('file')->getSize();
            //这里可根据配置文件的设置，做得更灵活一点
            if($size > 2*1024*1024){
                $error = new MessageBag([
                    'title'   => '上传文件不能超过2M',
                ]);
                return back()->with(compact('error'));    
            }
            //判断文件是否是通过HTTP POST上传的
            $realPath = $request->file('file')->getRealPath();

            if(!$realPath){
                $error = new MessageBag([
                    'title'   => '非法上传',
                ]);
                return back()->with(compact('error'));    
            }

            $list=$request->except("_token");
            $file = $list['file'];
            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 后缀名
            if($ext!=="xlsx"){
                $error = new MessageBag([
                    'title'   => '文件格式错误！',
                ]);
                return back()->with(compact('error'));
            }
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            // 上传后的文件名
            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
            move_uploaded_file($realPath,'storage/uploads/'.$filename); 
            $orders=crm_deal::find($id)->deal_orderid;
            Excel::load('storage/uploads/'.$filename, function($reader) use ($id) 
            {
                $reader = $reader->getSheet(0);//excel第一张sheet
                $results = $reader->toArray();
                unset($results[0]);//去除表头
                if ($results)
                {
                    $kehu=crm_customer::find(crm_deal::find($id)->deal_customer_id);
                    $order=crm_deal::find($id)->deal_orderid;
                    foreach ($results as $key => $value)
                    {
                        $data = [];
                        $data['tourist_name'] = $value[0] == null ? '':trim($value[0]);
                        $data['tourist_sex'] = $value[1] == null ? '' : trim($value[1]);
                        $data['tourist_phone'] = $value[2] == null ? '' : trim($value[2]);
                        $data['tourist_number'] = $value[3] == null ? '' : trim($value[3]);
                        $data['tourist_type'] = $kehu->customer_type;
                        $data['tourist_typename'] = $kehu->customer_danwei;
                        $data['deal_id']=$id;
                        $data['order_id']=$order;
                        $data['tourist_userid']=Admin::user()->id;
                        $data['tourist_shengri']=substr($value[3],-8,4);
                        $res = \DB::table('crm_tourist')->insertGetId($data);
                    }
                    
                }
            });
            @unlink('storage/uploads/'.$filename);
            $success = new MessageBag([
                'title'   => '上传成功',
            ]);
            return redirect(admin_url('crm_order/'.$orders.'/edit'))->with(compact('success'));
           
        }
    }
    public function ajax8()
    {
        $id = $_GET['v'];
        $list = \DB::table('crm_hetong')->where('statue',2)->where('type',crm_hetongtype::all()->where('title',$id)->pluck('id')[0])->where('users_id',Admin::user()->username)->pluck('hetong');
        return json_encode($list);
    }

    // 回访记录调查
    protected function diaocha($id)
    {
        return Admin::grid(crm_dchuifang::class, function (Grid $grid) use ($id) {
            $grid->model()->where('deal_id', $id);
            $grid->id("序号");
            $grid->title("标题");
            $grid->date("回访日期");
            $grid->statue("状态")->display(function () {
                $list=['1'=>'未回访','2'=>'已回访'];
                return $list[$this->statue];
            });
            $grid->tools(function ($tools) use ($id) {
                    $tools->append(new XinzengGender());
                    $list=crm_manyidu::where('deal_id',$id)->first();
                    if($list){
                        $tools->append(new ManyixiangqingGender($list)); 
                    }else{
                        $tools->append(new ManyiduGender()); 
                    }
                    $yixiang=crm_diaocha::where("deal_id",$id)->first();
                    if($yixiang){
                        $yixiangxiangqing=crm_diaocha::where("deal_id",$id)->get();
                        $tools->append(new YixiangGender($yixiangxiangqing));
                        $tools->append(new YixiangtianjiaGender());
                        $url=json_encode(admin_url('crm_order/yixiangtianjia').'/'.$id);
                        $script_addone=<<<EOT
                        $("#yixiangtianjia").attr("href",$url);
EOT;
                Admin::script($script_addone);
                    }else{
                        $tools->append(new YixiangtianjiaGender());
                        $url=json_encode(admin_url('crm_order/yixiangtianjia').'/'.$id);
                        $script_addone=<<<EOT
                        $("#yixiangtianjia").attr("href",$url);
EOT;
                Admin::script($script_addone);
                    }

            });
            $grid->actions(function ($actions) {
                $actions->disableDelete();//禁用删除按钮
                $actions->disableEdit();//禁用编辑按钮
                if($actions->row->statue==1){
                    $actions->append('<a href="javascript:" id="xiugaiba'.$actions->getKey().'"  class="btn btn-sm btn-danger">未回访</a>');
                }else{
                    $actions->append('<a href="javascript:" class="btn btn-sm btn-primary">已回访</a>');
                }
                $ddd=$actions->getKey();
                $script_addtwo=<<<EOT
                $("#xiugaiba$ddd").click(function(){
                    $.ajax({
                        url: "/admin/gdindex/ajax10",
                        type: "get",
                        dataType: "json",
                        data: {'v': $ddd},
                        success:function(data){
                            $.pjax.reload('#pjax-container');
                            toastr.success('操作成功');
                        }
                    }); 
                })
EOT;
                Admin::script($script_addtwo);      
            });
            $url=json_encode(admin_url('crm_order/huifangxinzeng/'.$id));
            $manyi=json_encode(admin_url('crm_order/manyidu/'.$id));
            $script_addones=<<<EOT
                $("#manyidu").attr("action",$manyi);
                $("#xinzeng").attr("href",$url);

EOT;
            Admin::script($script_addones);
            $grid->disableCreation();//禁用创建
            $grid->disableFilter();//禁用查询过滤器
            $grid->disableExport();//禁用导出按钮
            $grid->disableRowSelector();//禁用行选择
        });
        
    }
    // 回访记录新增页面
    public function huifangxinzeng($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('回访记录管理');
            $content->description('添加');
            $order=crm_deal::find($id)->deal_orderid;
            $form=new Form();
            $form->action(admin_url('crm_order/huifangtianjia/'.$order));
            $form->date('date', '回访时间')->format('YYYY-MM-DD');
            $form->text('title','回访标题');
            $form->hidden('deal_id','成交单ID')->default($id);
            $form->hidden('orderid','工单ID')->default($order);
            $form->hidden('userid','员工ID')->default(Admin::user()->id);
            $form->hidden('statue','状态')->default(1);
            $content->body($form);
        });
    }
    // 回访记录执行添加
    public function huifangtianjia(Request $request,$id)
    {
        $list=$request->except("_token");
        $rule=[
            'date'=>'required',
            'title'=>'required',
        ];
        $mess=[
            'date.required'=>'回访日期必须输入',
            'title.required'=>'回访标题必须输入',
            
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $res=crm_dchuifang::create($list);
            if($res){
                $success = new MessageBag([
                    'title'   => '添加成功',
                ]);
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '添加失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }
    }
    // 满意度添加
    public function manyidu(Request $request,$id)
    {
        //前端验证不得为空
        $list=$request->except("_token");
        $rule=[
            'manyidu'=>'required',
        ];
        $mess=[
            'manyidu.required'=>'满意度评分必须输入',
            
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $list['deal_id']=$id;
            $list['date']=date("y-m-d h:i:s");
            $res=crm_manyidu::create($list);
            if($res){
                $success = new MessageBag([
                    'title'   => '评分成功',
                ]);
                $order=crm_deal::find($id)->deal_orderid;
                return redirect(admin_url('crm_order/'.$order.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '评分失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }
        
    }
    // 下次意向调查
    public function yixiangtianjia($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('收款管理');
            $content->description('添加');
            $form=new Form();
            $order=crm_deal::find($id)->deal_orderid;
            $form->action(admin_url('crm_order/dctianjia').'/'.$order);
            $form->date('date', '下次意向旅游日期')->format('YYYY-MM-DD');
            $res=crm_route::where("parent_id",0)->get()->pluck("title","title");
            $form->select('type', '下次意向旅游类型')->options($res);
            $didian=crm_route::where("parent_id",crm_route::where("parent_id",0)->first()->pluck("id")[0])->get()->pluck("title","title");
            $form->select('didian', '下次意向旅游地点')->options($didian);
            $kehu=crm_customer::find(crm_deal::find($id)->deal_customer_id);
            $form->hidden('customer_id')->default($kehu->customer_name);
            $form->hidden('lurudate')->default(date("y-m-d h:i:s"));
            $form->hidden('deal_id')->default($id);
            $form->hidden('yuangong')->default(Admin::user()->id);
             $script_addones=<<<EOT
                    $(".type").change(function(){
                        var id=$(".type").val();
                        $.ajax({
                            url: "/admin/gdindex/ajax9",
                            type: "get",
                            dataType: "json",
                            data: {'v': id},
                            success:function(data){
                                if(data){
                                    var hh="<option value=\"请选择\">请选择<\/option>";
                                    for(var i=0;i<data.length;i++){
                                        hh +="<option value="
                                        hh +=data[i].title
                                        hh +=" >"
                                        hh +=data[i].title
                                        hh +="<\/option>";
                                    }
                                }else{
                                    var hh=" ";
                                }
                                $(".didian").html(hh);
                            }
                        }); 
                    })

EOT;
            Admin::script($script_addones);
            $content->body($form);
        });
    }
    // 意向添加
    public function dctianjia(Request $request,$id)
    {
        $list=$request->except("_token");
        $rule=[
            'date'=>'required',
            'type'=>'required',
            'didian'=>'required',
           
        ];
        $mess=[
            'date.required'=>'下次意向日期必须输入',
            'type.required'=>'下次意向旅游类型必须输入',
            'didian.required'=>'下次意向旅游地点必须输入',
            
        ];
        $validator =  Validator::make($list,$rule,$mess);
        if($validator->passes()){
            //执行添加
            $res=crm_diaocha::create($list);
            if($res){
                $success = new MessageBag([
                    'title'   => '添加成功',
                ]);
                return redirect(admin_url('crm_order/'.$id.'/edit'))->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '添加失败',
                ]);
                return back()->with(compact('error'));    
            }
        }else{
            return back()->withErrors($validator);
        }
    }
    // 下次意向调查
    public function ajax9()
    {
        $id = $_GET['v'];
        if($id){
            $aa=crm_route::where("title",$id)->first()->id;
            $list = \DB::table('crm_route')->where('parent_id','=',$aa)->get();
            return json_encode($list);
        }else{
            return json_encode("");
        }
    }
    public function ajax10()
    {
        $id = $_GET['v'];
        if($id){
            $list=crm_dchuifang::find($id);
            $list->statue=2;
            $res=$list->save();
            return json_encode($res);
        }else{
            return json_encode("");
        }
    }
    public function ajax11()
    {
        $id = $_GET['v'];
        if($id){
            $list=crm_account::find($id)->account_number;
            return json_encode($list);
        }else{
            return json_encode("");
        }
    }
}
